using ServiceStack.Redis;

namespace Aurora.Redis.ServiceStackRedis;

/// <summary>
/// redis 工厂类
/// </summary>
public class ServiceStackRedisFactory
{
    private static PooledRedisClientManager _pooledRedisClientManager;
    private static readonly object _obj = new();

    private ServiceStackRedisFactory()
    {
    }

    /// <summary>
    /// 获取实例
    /// </summary>
    /// <returns></returns>
    public static RedisClient Get()
    {
        if (_pooledRedisClientManager == null)
        {
            lock (_obj)
            {
                if (_pooledRedisClientManager == null)
                {
                    CreatePool();
                }
            }
        }

        return _pooledRedisClientManager.GetClient() as RedisClient;
    }

    private static ServiceStackRedisConfig Config { get; set; }

    /// <summary>
    /// 创建池
    /// </summary>
    private static void CreatePool()
    {
        _pooledRedisClientManager = new PooledRedisClientManager(Config.Write, Config.Read,
            new RedisClientManagerConfig()
            {
                MaxWritePoolSize = Config.MaxWritePoolSize,
                MaxReadPoolSize = Config.MaxReadPoolSize,
                DefaultDb = Config.DefaultDb
            });
        _pooledRedisClientManager.ConnectTimeout = Config.ConnectionTimeout;
    }

    /// <summary>
    /// 配置redis 节点
    /// </summary>
    /// <param name="config"></param>
    public static void ConfigRedisNode(ServiceStackRedisConfig config)
    {
        Config = config;
    }
}